package com.fenghongzhang.messager_server;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.widget.Toast;

import androidx.annotation.NonNull;

/**
 * 在服务端的handler中会接收到客户端的消息，然后进行对应的处理
 */
public class MyService extends Service {


    //创建信使对象. -> 等待接收客户端的消息.
    @SuppressLint("HandlerLeak")
    Messenger messenger = new Messenger(new Handler(){
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            //接收客户发的消息
            Bundle data = msg.getData();
            String hi = data.getString("hi");
            Toast.makeText(MyService.this, hi, Toast.LENGTH_SHORT).show();

            //给客户度发一个消息
            Messenger clientMessenger = msg.replyTo; //空指针
            Message obtain = Message.obtain();
            Bundle bundle = new Bundle();
            bundle.putString("hello","你也好");
            obtain.setData(bundle);
            try {
                clientMessenger.send(obtain);
            } catch (RemoteException e) {
                e.printStackTrace();
            }

        }
    });


    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return messenger.getBinder();
    }
}
